package com.qf.controller;

import com.qf.DBUtil.RandomUtils;
import com.qf.pojo.Address;
import com.qf.pojo.Cart;
import com.qf.pojo.Order;
import com.qf.pojo.User;
import com.qf.service.AddressService;
import com.qf.service.CartService;
import com.qf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/10/3 19:33
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    CartService cartService;
    @Autowired
    AddressService addressService;

    @RequestMapping("/getOrderList")
    public ModelAndView getOrderList(HttpSession session, ModelAndView mav){
        User user = (User) session.getAttribute("user");
        if (user==null){
            mav.setViewName("redirect:/login.jsp");
            return mav;
        }else {
            List<Order> orders = orderService.findAllOrder(user.getId());

            mav.addObject("orderList",orders);
            mav.setViewName("forward:/orderList.jsp");
            return mav;
        }
    }

    @RequestMapping("/getOrderView")
    public ModelAndView getOrderView(HttpSession session, ModelAndView mav){
        User user = (User) session.getAttribute("user");
        if (user==null){
            mav.setViewName("redirect:/login.jsp");
            return mav;
        }else {
            List<Cart> carts = cartService.findByUid(user.getId());
            List<Address> addresses = addressService.findById(user.getId());
            mav.addObject("addList" ,addresses);
            mav.addObject("carts",carts);
            mav.setViewName("forward:/order.jsp");
            return mav;
        }
    }

    @RequestMapping("/addOrder")
    public ModelAndView addOrder(HttpSession session, ModelAndView mav,Integer aid) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            mav.setViewName("redirect:/login.jsp");
            return mav;
        } else {
            List<Cart> cartList = cartService.findByUid(user.getId());
            Order order = orderService.addOrder(user.getId(),aid);
                mav.addObject("order",order);
                mav.setViewName("forward:/orderSuccess.jsp");
                return mav;
        }
    }

}
